import java.util.ArrayList;
import java.util.List;

public class Solution39 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> ans=new ArrayList<>();
        List<Integer> temp=new ArrayList<>();
        dfs(0,0,target,candidates,temp,ans);
        return ans;
    }

    private void dfs(int k, int sum, int target, int[] candidates, List<Integer> temp, List<List<Integer>> ans) {
        if (sum>target){
            return;
        }
        if (sum==target){
            ans.add(new ArrayList<>(temp));
            return;
        }
        if (k==candidates.length){
            return;
        }
        dfs(k+1,sum,target,candidates,temp,ans);
        int t=1;
        while (sum+t*candidates[k]<=target){
            temp.add(candidates[k]);
            dfs(k+1,sum+t*candidates[k],target,candidates,temp,ans);
            t++;
        }
        while (t>1){
            temp.remove(temp.size()-1);
            t--;
        }
    }

    public static void main(String[] args) {
        System.out.println(new Solution39().combinationSum(new int[]{2,3,6,7},7));
    }


}
